#include "myUI.h"
#include "lvgl.h"
#include <stdio.h>
// #include "/src/misc/lv_mem.h"
#include <stdlib.h>
#include <string.h>
#include <TFT_eSPI.h>
#include "touch.h"
#include "motor.h"

/*******************************            hardware init lcd   ***************************************** */

static const uint16_t screenWidth = 240;
static const uint16_t screenHeight = 320;
static lv_disp_draw_buf_t disp_buf;
static lv_color_t buf[screenWidth * 30];

TFT_eSPI my_lcd = TFT_eSPI();

#if USE_LV_LOG != 0
/* Serial debugging */
void my_print(const char *buf)
{
  Serial.printf(buf);
  Serial.flush();
}
#endif

/* Display flushing */
void my_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p)
{
  uint32_t w = (area->x2 - area->x1 + 1);
  uint32_t h = (area->y2 - area->y1 + 1);
  my_lcd.setAddrWindow(area->x1, area->y1, w, h);
  my_lcd.pushColors((uint16_t *)&color_p->full, w * h, true);
  lv_disp_flush_ready(disp);
}

/* Reading input device (simulated encoder here) */
void my_touchpad_read(lv_indev_drv_t *indev_driver, lv_indev_data_t *data)
{
  if (touch_has_signal())
  {
    if (touch_touched())
    {
      data->state = LV_INDEV_STATE_PR;

      /*Set the coordinates*/
      data->point.x = touch_last_x;
      data->point.y = touch_last_y;
    }
    else if (touch_released())
    {
      data->state = LV_INDEV_STATE_REL;
    }
  }
  else
  {
    data->state = LV_INDEV_STATE_REL;
  }
}

void UI_Init(void)
{
  Serial.begin(115200); /* prepare for possible serial debug */
  String LVGL_Arduino = "Hello Arduino! ";
  LVGL_Arduino += String('V') + lv_version_major() + "." + lv_version_minor() + "." + lv_version_patch();
  my_lcd.init();
  // my_lcd.setRotation(1);
  touch_init(my_lcd.width(), my_lcd.height(), my_lcd.getRotation());
  lv_init();
  delay(10);

#if USE_LV_LOG != 0
  lv_log_register_print_cb(my_print); /* register print function for debugging */
#endif

  lv_disp_draw_buf_init(&disp_buf, buf, NULL, screenWidth * 30);

  /*Initialize the display*/
  static lv_disp_drv_t disp_drv;
  lv_disp_drv_init(&disp_drv);
  disp_drv.hor_res = my_lcd.width();
  disp_drv.ver_res = my_lcd.height();
  disp_drv.flush_cb = my_disp_flush;
  disp_drv.draw_buf = &disp_buf;
  lv_disp_drv_register(&disp_drv);

  /*Initialize the (dummy) input device driver*/
  static lv_indev_drv_t indev_drv;
  lv_indev_drv_init(&indev_drv);
  indev_drv.type = LV_INDEV_TYPE_POINTER;
  indev_drv.read_cb = my_touchpad_read;
  lv_indev_drv_register(&indev_drv);

  /* Create simple label */
  // lv_obj_t *label = lv_label_create( lv_scr_act() );
  // lv_label_set_text( label, LVGL_Arduino.c_str() );
  // lv_obj_align( label, LV_ALIGN_CENTER, 0, 0 );

  // uncomment one of these demos
  //  lv_demo_widgets();            // OK
  // lv_demo_benchmark();          // OK
  // lv_demo_keypad_encoder();     // works, but I haven't an encoder
  // lv_demo_music();              // NOK
  // lv_demo_stress();             // seems to be OK

  // lv_obj_t * label1 = lv_label_create( lv_scr_act() );
  // lv_obj_align( label1, LV_ALIGN_CENTER, 0,-10 );
  // lv_label_set_text( label1, "Hello World!" );

  // lv_obj_t* slider = lv_slider_create(lv_scr_act());
  // lv_obj_set_size(slider, 200, 20);
  // lv_obj_align(slider, LV_ALIGN_CENTER, 0, 10);
  loginPage();
}

/*******************************            page soft ware   ***************************************** */

typedef struct
{
  int currentSpeed;
  int targetSpeed;
  int currentAngle;
  int targetAngle;
  lv_obj_t *pageHome;
  lv_obj_t *pageLogin;
  lv_obj_t *currentSpeedLabel;
  lv_obj_t *targetSpeedLabel;
  lv_obj_t *currentAngleLabel;
  lv_obj_t *targetAngleLabel;
  lv_obj_t *imgPointer;
  float imgPointerAngle;
  float imgPointerAngleLast;
  int imgPointerFullRotation;
  int imgPointerDirection;

} S_UI_MESSAGE;

S_UI_MESSAGE s_UI;

// 定时器回调函数
static void timer_callback(lv_timer_t *timer)
{
  // 获取定时器的用户数据
  // TimerUserData *userData = (TimerUserData *)timer->user_data;
  // 隐藏 loginPage
  lv_obj_add_flag(s_UI.pageLogin, LV_OBJ_FLAG_HIDDEN);
  // 显示 wifiLabel
  lv_obj_clear_flag(s_UI.pageHome, LV_OBJ_FLAG_HIDDEN);

  // 删除定时器，避免重复触发
  // lv_timer_del(timer);
  printf("loginTimerCallBack \n");
}

// 定义旋转动画的参数
#define ROTATION_DURATION 1000 // 单次旋转动画的持续时间（ms）
#define ROTATION_COUNT 5       // 正反转次数

static lv_anim_t anim_rotate;
// static lv_obj_t * arc;
static int8_t direction = 1; // 方向：1=正转，-1=反转
static uint8_t count = 0;    // 当前旋转计数
// // 动画回调函数：更新旋转角度
// static void set_angle(void * obj, int32_t angle) {
//     lv_arc_set_rotation(obj, angle);
// }



void speedSliderEventCb(lv_event_t *e)
{
  char tempBuf[100] = {0};
  lv_event_code_t code = lv_event_get_code(e);
  lv_obj_t *slider = lv_event_get_target(e);
  if (code == LV_EVENT_VALUE_CHANGED)
  {
    s_UI.targetSpeed = lv_slider_get_value(slider);
    lv_memset_00(tempBuf, sizeof(tempBuf));
    sprintf(tempBuf, "targetRPM: %d rpm", s_UI.targetSpeed);
    lv_label_set_text(s_UI.targetSpeedLabel, tempBuf);
    motor1->setRpm(s_UI.targetSpeed);
  }
}

void widgitEvent(lv_event_t *e)
{
  lv_event_code_t code = lv_event_get_code(e);
  lv_obj_t *obj = lv_event_get_target(e);
  lv_indev_t *indev = lv_indev_get_act();

  if (code == LV_EVENT_PRESSED || code == LV_EVENT_PRESSING)
  {
    lv_point_t touch_point;
    lv_indev_get_point(indev, &touch_point);

    lv_area_t img_coords;
    lv_obj_get_coords(s_UI.imgPointer, &img_coords);
    lv_coord_t img_height = lv_obj_get_height(s_UI.imgPointer);

    // 计算旋转中心绝对坐标 (图片左边缘中点)
    lv_point_t pivot = {
        .x = img_coords.x1,                 // 图片左上角X坐标
        .y = img_coords.y1 + img_height / 2 // 图片顶部Y坐标 + 高度一半
    };

    // 计算相对坐标差
    float dx = touch_point.x - pivot.x;
    float dy = touch_point.y - pivot.y;

    float angle = atan2f(dy, dx) * (180 / M_PI);
    if (angle < 0)
      angle += 360; // 恢复角度修正

    // 计算角度差值（考虑360度循环）
    float delta = angle - s_UI.imgPointerAngleLast;
    if (delta > 180)
      delta -= 360; // 处理顺时针跨圈
    if (delta < -180)
      delta += 360; // 处理逆时针跨圈
      
    // 累加总角度（保留小数精度）
    s_UI.imgPointerAngle += delta;

    // 自动计算旋转方向和圈数
    s_UI.imgPointerDirection = (delta >= 0) ? 1 : -1;
    s_UI.imgPointerFullRotation = (int)(s_UI.imgPointerAngle / 360);

    // 更新最后角度值（使用原始角度值保持循环）
    s_UI.imgPointerAngleLast = angle;

 
    lv_img_set_angle(s_UI.imgPointer, (int16_t)(angle * 10)); // 0.1度单位
    lv_label_set_text_fmt(s_UI.targetAngleLabel, "Value:%.2f", s_UI.imgPointerAngle);
    motor1->setAngle(s_UI.imgPointerAngle);
  }
}


void titie_1ShowEvent(lv_event_t *e)
{

}


void titie_1HideEvent(lv_event_t *e)
{
  // motor1->stop();
}


void titie_2ShowEvent(lv_event_t *e)
{

}

void titie_2HideEvent(lv_event_t *e)
{

}


void loginPage(void)
{
  char tempBuf[100] = {0};
  const lv_font_t *font;
  font = &lv_font_montserrat_14;
  // 设置当前活动屏幕的背景颜色为白色


  s_UI.pageHome = lv_obj_create(lv_scr_act());
  lv_obj_set_size(s_UI.pageHome, lv_pct(100), lv_pct(100));
  lv_obj_align(s_UI.pageHome, LV_ALIGN_CENTER, 0, 0); // 确保 pageHome 居中对齐
  lv_obj_set_style_bg_color(s_UI.pageHome, lv_color_make(255, 255, 255), LV_STATE_DEFAULT);
  lv_obj_set_style_pad_all(s_UI.pageHome, 0, LV_STATE_DEFAULT); // 移除 pageHome 的所有边距

  /* 创建平铺视图页面 */
  lv_obj_t *tileview = lv_tileview_create(s_UI.pageHome); /* 创建平铺视图 */
  lv_obj_set_size(tileview, lv_pct(100), lv_pct(100));    /* 设置平铺视图大小 */
  /* 添加页面 1 */
  lv_obj_t *tile_1 = lv_tileview_add_tile(tileview, 0, 0, LV_DIR_RIGHT);
  lv_obj_set_size(tile_1, lv_pct(100), lv_pct(100));
  lv_obj_add_event_cb(tile_1, titie_1ShowEvent, LV_EVENT_SCREEN_LOADED, NULL);
  lv_obj_add_event_cb(tile_1, titie_1HideEvent, LV_EVENT_SCREEN_UNLOADED, NULL);



  /* 添加页面 2 */
  lv_obj_t *tile_2 = lv_tileview_add_tile(tileview, 1, 0, LV_DIR_LEFT | LV_DIR_RIGHT);
  lv_obj_set_size(tile_2, lv_pct(100), lv_pct(100));
  lv_obj_add_event_cb(tile_2, titie_2ShowEvent, LV_EVENT_SCREEN_LOADED, NULL);
  lv_obj_add_event_cb(tile_2, titie_2HideEvent, LV_EVENT_SCREEN_UNLOADED, NULL);
  /* 添加页面 3 */
  lv_obj_t *tile_3 = lv_tileview_add_tile(tileview, 2, 0, LV_DIR_LEFT);
  lv_obj_set_size(tile_3, lv_pct(100), lv_pct(100));

  // 页面1
  /* 设置页面内容 */
  lv_obj_t *label_1 = lv_label_create(tile_1); /* 创建标签 */

  lv_label_set_text(label_1, "speed");                         /* 设置文本内容 */
  lv_obj_set_style_text_font(label_1, font, LV_STATE_DEFAULT); /* 设置字体 */
  lv_obj_align(label_1, LV_ALIGN_TOP_MID, 0, 10);              /* 设置位置 */

  s_UI.currentSpeedLabel = lv_label_create(tile_1); /* 创建标签 */
  lv_obj_set_pos(s_UI.currentSpeedLabel, 10, 50);
  lv_memset_00(tempBuf, sizeof(tempBuf));
  sprintf(tempBuf, "curSpeed: %d km/h", s_UI.currentSpeed);
  lv_label_set_text(s_UI.currentSpeedLabel, tempBuf);

  s_UI.targetSpeedLabel = lv_label_create(tile_1); /* 创建标签 */
  lv_obj_set_pos(s_UI.targetSpeedLabel, 10, 80);
  lv_memset_00(tempBuf, sizeof(tempBuf));
  sprintf(tempBuf, "tarSpeed: %d km/h", s_UI.targetSpeed);
  lv_label_set_text(s_UI.targetSpeedLabel, tempBuf);

  lv_obj_t *speedSlider = lv_slider_create(tile_1);
  lv_obj_set_size(speedSlider, 200, 20);
  lv_obj_align(speedSlider, LV_ALIGN_CENTER, 0, 0);
  lv_slider_set_range(speedSlider, -MOTOR_RPM_MAX, MOTOR_RPM_MAX);
  lv_slider_set_value(speedSlider, 0, LV_ANIM_OFF);
  lv_obj_add_event_cb(speedSlider, speedSliderEventCb, LV_EVENT_VALUE_CHANGED, NULL);
  // lv_bar_set_mode(bar, LV_BAR_MODE_SYMMETRICAL);
  lv_slider_set_mode(speedSlider, LV_BAR_MODE_SYMMETRICAL);

  // 页面2
  lv_obj_t *label_2 = lv_label_create(tile_2);                 /* 创建标签 */
  lv_label_set_text(label_2, "position");                      /* 设置文本内容 */
  lv_obj_set_style_text_font(label_2, font, LV_STATE_DEFAULT); /* 设置字体 */
  lv_obj_align(label_2, LV_ALIGN_TOP_MID, 0, 10);              /* 设置位置 */

  s_UI.currentAngleLabel = lv_label_create(tile_2); /* 创建标签 */
  lv_obj_set_pos(s_UI.currentAngleLabel, 10, 50);
  lv_memset_00(tempBuf, sizeof(tempBuf));
  sprintf(tempBuf, "curpos: %d ", 20);
  lv_label_set_text(s_UI.currentAngleLabel, tempBuf);

  s_UI.targetAngleLabel = lv_label_create(tile_2); /* 创建标签 */
  lv_obj_set_pos(s_UI.targetAngleLabel, 10, 80);
  lv_memset_00(tempBuf, sizeof(tempBuf));
  sprintf(tempBuf, "tarPos: %d ", 30);
  lv_label_set_text(s_UI.targetAngleLabel, tempBuf);


  // 创建基础对象
  lv_obj_t *widgit = lv_obj_create(tile_2);
  lv_obj_clear_flag(widgit, LV_OBJ_FLAG_SCROLL_CHAIN);
  // 设置尺寸为正方形
  lv_obj_set_size(widgit, 180, 180);
  // 设置为圆形样式
  lv_obj_set_style_radius(widgit, LV_RADIUS_CIRCLE, LV_STATE_DEFAULT);
  // 设置背景颜色为红色
  lv_obj_set_style_bg_color(widgit, lv_color_make(255, 255, 255), LV_STATE_DEFAULT);
  // 设置边框宽度
  lv_obj_set_style_border_width(widgit, 5, LV_STATE_DEFAULT);
  // 设置边框颜色
  lv_obj_set_style_border_color(widgit, lv_color_make(255, 0, 0), LV_STATE_DEFAULT);
  lv_obj_add_flag(widgit, LV_OBJ_FLAG_SCROLL_ON_FOCUS); // 新增滚动焦点标志

  // 居中显示
  // lv_obj_center(widgit);
  lv_obj_align(widgit, LV_ALIGN_CENTER, 0, 30);

  LV_IMG_DECLARE(imagePointer);
  // 创建一个GIF对象
  s_UI.imgPointer = lv_img_create(widgit);
  // 将数据设置给对象
  //  lv_gif_set_src(obj_img,&pointer);
  lv_img_set_src(s_UI.imgPointer, &imagePointer);
  lv_obj_set_size(s_UI.imgPointer, 75, 20);
  lv_obj_update_layout(s_UI.imgPointer);     // 3. 强制更新布局
  lv_obj_refresh_self_size(s_UI.imgPointer); // 强制刷新尺寸计算
  lv_obj_align(s_UI.imgPointer, LV_ALIGN_CENTER, 37, 0);

  lv_obj_add_flag(widgit, LV_OBJ_FLAG_CLICKABLE);
  lv_obj_add_event_cb(widgit, widgitEvent, LV_EVENT_ALL, NULL);
  lv_obj_remove_style(widgit, NULL, LV_PART_SCROLLBAR);       /* 移除滚动条 */
  lv_obj_clear_flag(s_UI.imgPointer, LV_OBJ_FLAG_SCROLLABLE); // 禁止滚动
  lv_obj_clear_flag(widgit, LV_OBJ_FLAG_SCROLLABLE);          // 禁止滚动
  // 设置指针旋转中心（根据图片尺寸调整）

  lv_img_set_pivot(s_UI.imgPointer, 0, lv_obj_get_height(s_UI.imgPointer) / 2); // Y轴底部中心、

  // 创建中心点（方法1：使用标签控件）
  lv_obj_t *centerDot = lv_obj_create(widgit);
  lv_obj_set_size(centerDot, 10, 10);
  lv_obj_set_style_radius(centerDot, LV_RADIUS_CIRCLE, 0);
  lv_obj_set_style_bg_color(centerDot, lv_color_make(0, 255, 0), 0);
  lv_obj_align(centerDot, LV_ALIGN_CENTER, 0, 0);

  // 页面3
  lv_obj_t *labelWifi = lv_label_create(tile_3);                 /* 创建标签 */
  lv_label_set_text(labelWifi, LV_SYMBOL_WIFI);                  /* 设置文本内容 */
  lv_obj_set_style_text_font(labelWifi, font, LV_STATE_DEFAULT); /* 设置字体 */
  lv_obj_align(labelWifi, LV_ALIGN_TOP_RIGHT, 0, 10);            /* 设置位置 */

  // 创建一个GIF对象
  // 声名对象
  LV_IMG_DECLARE(rabitGif);
  lv_obj_t *obj_img = lv_gif_create(tile_3);
  // 将数据设置给对象
  lv_gif_set_src(obj_img, &rabitGif);
  lv_obj_align(obj_img, LV_ALIGN_CENTER, 0, 0);

  lv_obj_remove_style(tileview, NULL, LV_PART_SCROLLBAR); /* 移除滚动条 */
  // 初始时隐藏 wifiLabel
  lv_obj_add_flag(s_UI.pageHome, LV_OBJ_FLAG_HIDDEN);

  LV_FONT_DECLARE(chineseFont_songti);
  // 创建 loginPage
  s_UI.pageLogin = lv_obj_create(lv_scr_act());
  lv_obj_set_style_bg_color(s_UI.pageLogin, lv_color_make(0, 0, 0), LV_STATE_DEFAULT);
  lv_obj_set_size(s_UI.pageLogin, lv_pct(100), lv_pct(100));





  // 创建 loginLabel
  lv_obj_t *labelLogin = lv_label_create(s_UI.pageLogin);
  lv_obj_set_style_text_color(labelLogin, lv_color_make(255, 255, 255), LV_STATE_DEFAULT);
  lv_obj_set_style_text_font(labelLogin, &chineseFont_songti, LV_STATE_DEFAULT);
  lv_label_set_text(labelLogin, "美国有苹果");
  lv_obj_align(labelLogin, LV_ALIGN_CENTER, 0, -20);

  lv_obj_t *labelLogin1 = lv_label_create(s_UI.pageLogin);
  lv_obj_set_style_text_color(labelLogin1, lv_color_make(255, 255, 255), LV_STATE_DEFAULT);
  lv_obj_set_style_text_font(labelLogin1, &chineseFont_songti, LV_STATE_DEFAULT);
  lv_label_set_text(labelLogin1, "中国有菠萝");
  lv_obj_align(labelLogin1, LV_ALIGN_CENTER, 0, 20);


  lv_obj_t *labelName = lv_label_create(s_UI.pageLogin);
  lv_obj_set_style_text_color(labelName, lv_color_make(255, 0, 0), LV_STATE_DEFAULT);
  lv_obj_set_style_text_font(labelName,&lv_font_montserrat_28,LV_STATE_DEFAULT);
  lv_label_set_text(labelName, "POLO 1.2");
  lv_obj_align(labelName, LV_ALIGN_CENTER, 0, -110);

  lv_obj_t *labelName1 = lv_label_create(s_UI.pageLogin);
  lv_obj_set_style_text_color(labelName1, lv_color_make(255, 0, 0), LV_STATE_DEFAULT);
  lv_obj_set_style_text_font(labelName1,&lv_font_montserrat_28,LV_STATE_DEFAULT);
  lv_label_set_text(labelName1, "motor control");
  lv_obj_align(labelName1, LV_ALIGN_CENTER, 0, -80);


  // 创建一个定时器，每隔1000毫秒（1秒）调用一次回调函数
  lv_timer_t *timerLogin = lv_timer_create(timer_callback, 1000, NULL);
  // 设置重复次数为1次
  lv_timer_set_repeat_count(timerLogin, 1);
  // 启动定时器
  lv_timer_resume(timerLogin);
}
